package com.liangdemo.web.token;

import com.liangdemo.web.Service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * token验证拦截
 *
 * @author Mr.Liang
 * @date 2022/5/12 16:10
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static JwtUtils jwtUtils;
    private static UserService userService;

    /**
     * 使用以下方式代替@Autowired的注入方式
     */
    @Resource
    private void setJwtUtils(JwtUtils jwtUtils) {
        TokenInterceptor.jwtUtils = jwtUtils;
    }

    @Resource
    private void setUserService(UserService userService) {
        TokenInterceptor.userService = userService;
    }

    Map map = new HashMap<String, Object>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = request.getHeader("token");//获取token
        if (token != null) {
            if (!jwtUtils.isTokenExpired(token)) {
                map.put("code", 401);
                map.put("msg", "token过期");
            } else {
                /**
                 * 获取token
                 * 根据token获取用户id
                 * 根据用户id去查询用户信息
                 * 判断用户是否登录
                 */
                if (judge(token)) {
                    return true;
                } else {
                    map.put("code", 401);
                    map.put("msg", "用户不存在请重新登录 ");
                }
            }

        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = null;
        try {
//            if (token == null) {
//                map.put("code", 401);
//                map.put("msg", "未携带token");
//            }
            response.getWriter().write(new ObjectMapper().writeValueAsString(map));
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return false;
    }

    /**
     * 判断token是否正确
     *
     * @param token
     * @return
     */
    private boolean judge(String token) {
        if (userService.getById(jwtUtils.parseJwt(token).getId()) != null) {
            return true;
        } else {
            return false;
        }
    }


}

